#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

#ifndef APP_VERSION
#define APP_VERSION ""
#endif
Widget::Widget(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("全景图查看器");

    m_layout = new QVBoxLayout();
    m_layout->setSpacing(0);
    m_layout->setContentsMargins(1, 1, 1, 1);
    openglWidget = new OpenglWidget(this);
    imageNo360Widget = new imageNo360(this);
    m_layout->addWidget(openglWidget);
    m_layout->addWidget(imageNo360Widget);

    centralWidget()->setLayout(m_layout);
    settingsDialog = new settingQDialog(this);
    // 工具栏
    QWidget *spacer = new QWidget(); // 添加左侧侧弹簧保持对称
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->toolBar->addWidget(spacer);
    ui->toolBar->addAction(ui->action_open);
    ui->toolBar->addAction(ui->action_pre);
    ui->toolBar->addAction(ui->action_next);
    ui->toolBar->addAction(ui->action_setup);
    ui->toolBar->addAction(ui->action_help);

    QWidget *spacer2 = new QWidget(); // 添加右侧弹簧保持对称
    spacer2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->toolBar->addWidget(spacer2);
    ui->action_next->setEnabled(false);
    ui->action_pre->setEnabled(false);
    // 启用拖放功能
    setAcceptDrops(true);

    // 后台加载
    thread = new QThread(this);
    preloading = new ImagePreloading();
    preloading->moveToThread(thread);
    connect(openglWidget, &OpenglWidget::loadImagFilsh, this, [this]()
            {
                openglWidget->show();
              imageNo360Widget->hide();  });

    connect(this, &Widget::signalLoadImage, preloading, &ImagePreloading::loadImage);
    connect(this, &Widget::signalClearImage, preloading, &ImagePreloading::clearImage);
    connect(preloading, &ImagePreloading::imageLoaded, this, [this](QImage image)
            { openglWidget->setImage(image); });
    thread->start();
    // 状态栏
    m_statusbar_message = new QLabel();
    m_statusbar_app_version = new QLabel();
    m_page_label_count = new QLabel();
    m_page_lable_cur = new QLabel();
    m_statusbar_message->setTextInteractionFlags(Qt::TextSelectableByMouse);
    m_statusbar_message->setCursor(Qt::IBeamCursor);
    ui->statusbar->addWidget(m_page_label_count);
    ui->statusbar->addWidget(m_page_lable_cur);
    ui->statusbar->addWidget(m_statusbar_message, 1);

    ui->statusbar->addWidget(m_statusbar_app_version);

    connect(settingsDialog, &settingQDialog::accepted, this, [this]()
            { 
            sets.setValue("mouseSensitivity", settingsDialog->ui->mouseSensitivity->value()); 
            sets.setValue("mouseFov", settingsDialog->ui->mouseFov->value()); 
            sets.setValue("image_preloading", settingsDialog->ui->image_preloading->isChecked()); });
    connect(ui->action_setup, &QAction::triggered, this, [this]()
            { 
                settingsDialog->loadSettings();
                settingsDialog->exec(); });
    connect(ui->action_open, &QAction::triggered, this, [this]()
            {
            path = QFileDialog::getExistingDirectory(this, "选择文件夹");
            if (!path.isEmpty())
            {
                loadDir();
            } });
    connect(ui->action_next, &QAction::triggered, this, [this]()
            { 
                if(imageFileNames.size() ==1)
                    return;
                currentImageIndex++;
                loadImages(); });
    connect(ui->action_pre, &QAction::triggered, this, [this]()
            { 
                if(imageFileNames.size() ==1)
                    return;
                currentImageIndex--;
                loadImages(); });
    connect(ui->action_help, &QAction::triggered, this, [this]()
            { help(); });
    m_statusbar_app_version->setText(QString("版本:%1        作者：XXD").arg(APP_VERSION));
}

void Widget::closeEvent(QCloseEvent *event)
{
    thread->quit();
    thread->wait();
}
Widget::~Widget()
{
    delete openglWidget;
    delete imageNo360Widget;
    delete preloading;
    delete ui;
}
bool Widget::is360(QString &file)
{
    QImageReader reader(file);
    auto size = reader.size();

    if (size.width() * 1.0 / size.height() == 2.0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
void Widget::loadImages()
{
    if (imageFileNames.size() <= 0)
        return;
    if (currentImageIndex < 0)
        currentImageIndex = imageFileNames.size() - 1;

    m_page_label_count->setText(QString("共%1张").arg(imageFileNames.size()));
    m_page_lable_cur->setText(QString(" 第%1张").arg(currentImageIndex + 1));

    if (currentImageIndex % imageFileNames.size() == imageFileNames.size() - 1)
        ui->action_next->setEnabled(false);
    else
        ui->action_next->setEnabled(true);
    if (currentImageIndex % imageFileNames.size() == 0)
        ui->action_pre->setEnabled(false);
    else
        ui->action_pre->setEnabled(true);

    if (is360(imageFileNames[currentImageIndex % imageFileNames.size()]))
    {

        if (sets.value("image_preloading", false).toBool())
        {
            emit signalLoadImage(imageFileNames, currentImageIndex);
        }
        else
        {
            emit signalClearImage();
            QImage image(imageFileNames[currentImageIndex % imageFileNames.size()]);
            openglWidget->setImage(image);
            imageNo360Widget->hide();
            openglWidget->show();
        }
    }
    else
    {

        if (sets.value("image_preloading", false).toBool())
        {
            emit signalLoadImage(imageFileNames, currentImageIndex);
        }
        QImage image(imageFileNames[currentImageIndex % imageFileNames.size()]);
        imageNo360Widget->setImage(image);
        openglWidget->hide();
        imageNo360Widget->show();
    }
    loadImagesInfo();
}
void Widget::loadImagesInfo()
{
    QImageReader image(imageFileNames[currentImageIndex % imageFileNames.size()]);
    message.clear();
    message += "当前文件:";
    message += imageFileNames[currentImageIndex % imageFileNames.size()];
    message += QString("        图像尺寸:%1X%2").arg(image.size().width()).arg(image.size().height());

    // 自动选择KB或MB单位
    QFileInfo info(imageFileNames[currentImageIndex % imageFileNames.size()]);
    qint64 size = info.size();
    QString sizeStr;
    if (size < 1024 * 1024)
    { // 小于1MB
        sizeStr = QString("%1KB").arg(size / 1024.0, 0, 'f', 2);
    }
    else
    {
        sizeStr = QString("%1MB").arg(size / (1024.0 * 1024.0), 0, 'f', 2);
    }
    message += QString("        文件大小:%1").arg(sizeStr);

    m_statusbar_message->setText(message);
}
void Widget::loadDir()
{
    QStringList filters;
    filters << "*.jpg" << "*.png" << "*.jpeg";
    QDirIterator it(path, filters, QDir::Files);
    imageFileNames.clear();
    while (it.hasNext())
    {
        imageFileNames.append(it.next());
    }
    currentImageIndex = 0;
    preloading->clearImage();
    loadImages();
}
void Widget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space || event->key() == Qt::Key_Right || event->key() == Qt::Key_Down || event->key() == Qt::Key_PageDown)
    {
        ui->action_next->trigger();
    }
    else if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Up || event->key() == Qt::Key_PageUp)
    {
        ui->action_pre->trigger();
    }
    else if (event->key() == Qt::Key_F1)
    {
        help();
    }
}
void Widget::help()
{
    QMessageBox::information(this, "帮助", R"(
<html><head/><body><p>
<span style=" font-size:11pt; font-weight:700;">快捷键说明:</span><br/>
<span style=" font-weight:700;"><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;帮&nbsp;&nbsp;&nbsp;助：</span><span style=" color:#0066cc;">&nbsp;&nbsp;F1</span></p><p>
<span style=" font-weight:700;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;下一张: </span>  <span style=" color:#0066cc;">&nbsp;&nbsp;空格/右方向键/下方向键/PageDown</span></p><p>
<span style=" font-weight:700;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;上一张：</span><span style=" color:#0066cc;">&nbsp;左方向键/上方向键/PageUp</span></p><p>
<span style=" font-weight:700;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;打开设置： </span><span style=" color:#0066cc;">Ctrl+s</span></p></body></html>
<span style=" font-weight:700;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;打开文件夹：</span><span style=" color:#0066cc;">Ctrl+o</span></p><p>
<span style=" font-size:11pt; font-weight:700;color:#ff0000;">注意:</span><br/>
<span style="  font-weight:700;color:#ff0000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;本查看器是根据图像长宽比是否为2来判断是不是360全景图，如果不是2，就会被当作普通图片打开。这个特征不是100%准确！！！</span></p><p>
    )");
}
void Widget::contextMenuEvent(QContextMenuEvent *event)
{
    // 如果事件发生在工具栏上，则忽略
    if (ui->toolBar->rect().contains(ui->toolBar->mapFromGlobal(event->globalPos())))
    {
        event->ignore();
        return;
    }
    QMainWindow::contextMenuEvent(event);
}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    // 检查拖入的内容是否包含文件
    if (event->mimeData()->hasUrls())
    {
        event->acceptProposedAction();
    }
}

void Widget::dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();
    if (mimeData->hasUrls())
    {
        QStringList pathList;
        QList<QUrl> urlList = mimeData->urls();
        QFileInfo dir(urlList[0].toLocalFile());
        path = dir.absoluteDir().path();
        loadDir();
    }
}
